//
//  ResultsViewController.m
//  YunGui
//
//  Created by Hanen 3G 01 on 16/4/27.
//  Copyright © 2016年 hanen. All rights reserved.
//

#import "ResultsViewController.h"
#import "PopTipView.h"
#import "SQButton.h"
#import "NetModel.h"
#import "CabinetCheckDetailController.h"
#import "YGNavigationController.h"
#import "SettingButton.h"
//#import "NetModel.h"
#import "RuleViewController.h"
#import "CabinetCheckController.h"
#import "ZLAlertView.h"
#import "MyTextView.h"

@interface ResultsViewController ()<UITextViewDelegate,PopTipViewDelegate>
{
    UIScrollView  *_scrollView;
    
    UIView  *_topView;
    
    UIView  *_thirdView;
    
      CGFloat   space;
    CGFloat  lastY;
    
    MyTextView  *writeRecodView;
    PopTipView  *_PopJudgeCheck;
    
    UILabel  *recordLabel;
    
    NSString *isOKOrBad;
    
        SettingButton *_OKBtn;
        SettingButton *_BadBtn;
    
        SettingButton *_lastBtn;//记录一个按钮
    
}
@end

@implementation ResultsViewController

- (void)viewDidLoad {
     [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.titleView = [ViewTool getNavigitionTitleLabel:@"检测结果"];
     self.navigationItem.leftBarButtonItem = [ViewTool getBackBarButtonItemWithTarget:self WithAction:@selector(backController)];
    [ViewTool setNavigationBar:self.navigationController.navigationBar];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(postCabinetCheck)];
     space = [UIView getWidth:10.0f];
   
    
    
    
    [self addScrollView];
    [self addSubviews];
    [self addThirdView];
    
//    _PopJudgeCheck = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:250.0f], [UIView getHeight:130.0f])];
//    //    _PopJudgeCheck.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f - 64);
////    _PopJudgeCheck.backView.enabled = NO;
//    _PopJudgeCheck.BackEnabled = NO;
//    _PopJudgeCheck.tipsLabel.text = @"提示:请选择是否合格？";
//    _PopJudgeCheck.lefttext = @"不合格";
//    _PopJudgeCheck.righText = @"合格";
//    _PopJudgeCheck.isShowImage = YES;
////    _PopJudgeCheck.isShowImage 
//    _PopJudgeCheck.delegate = self;
//    [_PopJudgeCheck showToView:self.view];
    
}
//提交
- (void)postCabinetCheck
{
//    if (writeRecodView.text.length == 0) {
////        [Tools showMessage:@"请填写备注" view:self];
////        return;
//    }
    if (isOKOrBad == nil){
            _PopJudgeCheck = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:250.0f], [UIView getHeight:130.0f])];
            //    _PopJudgeCheck.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f - 64);
        //    _PopJudgeCheck.backView.enabled = NO;
            _PopJudgeCheck.BackEnabled = NO;
            _PopJudgeCheck.tipsLabel.text = @"提示:请选择是否合格？";
            _PopJudgeCheck.lefttext = @"不合格";
            _PopJudgeCheck.righText = @"合格";
            _PopJudgeCheck.isShowImage = YES;
        //    _PopJudgeCheck.isShowImage
            _PopJudgeCheck.delegate = self;
            [_PopJudgeCheck showToView:self.view];

    }else{
        [SVProgressHUD show];
//         NSMutableDictionary *dict2 = [[NSUserDefaults standardUserDefaults] objectForKey:@"checkDict"];
    NSInteger userid = [[NSUserDefaults standardUserDefaults] integerForKey:@"userId"];
        int k ;
       
        if ([isOKOrBad isEqualToString:@"合格"]) {
            k = 1;
        }else{
            k = 2;
        }
        //self.checkType---> 0 1 2;
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithDictionary:@{@"method":@"app.branchCheck.check",@"check_id": self.checklID,@"type": self.checkType,@"status" : @(k),@"check_user_id" : @(userid)}];
        if (writeRecodView.text.length != 0) {
            [dict setObject:writeRecodView.text forKey:@"remark"];
        }
        
        //            [talkingArray removeAllObjects];
        NSDictionary *paramersDict = [DataTool addSignToDic:dict];
        NSLog(@"提交的参数%@",paramersDict);
        [DataTool postWithUrl:HEAD_URL parameters:paramersDict success:^(id data) {
            id backData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments | NSJSONReadingMutableContainers error:nil];
            NSLog(@"评定数据%@",backData);
            [SVProgressHUD dismiss];
            if([backData[@"status"] isEqualToString:@"SUCCESS"]){

            NSDictionary *dict = backData[@"data"];
                
                //创建一个消息对象
                NSNotification * notice = [NSNotification notificationWithName:@"guiti" object:nil userInfo:@{@"guiti":@"1"}];
                //发送消息
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            
//            BackCheckModel *model = [[BackCheckModel alloc] init];
//            [model setValuesForKeysWithDictionary:dict];
            

//                [Tools showMessage:@"评定成功" view:self];
//            [SVProgressHUD showWithStatus:@"评定成功"];
//            CabinetCheckDetailController *cabeVC = [[CabinetCheckDetailController alloc] init];
//            cabeVC.BackDict = dict;
//            [self.navigationController popToRootViewControllerAnimated:NO];
            int nextType = [dict[@"next_type"] intValue];
            int check_num = [dict[@"check_num"] intValue];
            for (UIViewController* v in self.navigationController.viewControllers) {
                NSLog(@"nextType:%d",nextType);
                
                if (nextType == 3){
                    if ([v isKindOfClass:[CabinetCheckController class]]) {
                        CabinetCheckController *cabVC = (CabinetCheckController *)v;
                        cabVC.isRefresh = YES;
                        [self.navigationController popToViewController:cabVC animated:NO];
                    }
                }else{
                    if (check_num == 0) {
                        if ([v isKindOfClass:[CabinetCheckController class]]) {
                            CabinetCheckController *cabVC = (CabinetCheckController *)v;
                            cabVC.isRefresh = YES;
                            [self.navigationController popToViewController:cabVC animated:NO];
                        }
                    }
                    if ([v isKindOfClass:[RuleViewController class]]) {
                        RuleViewController *cabeVC = (RuleViewController *)v;
                        cabeVC.BackDict = dict;
                        [self.navigationController popToViewController:v animated:NO];
                    }
                }
                
                
//                if (nextType != 3) {
//                    if ([v isKindOfClass:[RuleViewController class]]) {
//                        RuleViewController *cabeVC = (RuleViewController *)v;
//                        cabeVC.BackDict = dict;
//                        [self.navigationController popToViewController:v animated:NO];
//                    }
//                    
////                    CabinetCheckDetailController *cabeVC = [[CabinetCheckDetailController alloc] init];
////                    cabeVC.BackDict = dict;
////                    cabeVC.isRefresh = YES;
////                    [self.navigationController popToRootViewControllerAnimated:NO];
//                    
//                }else if(nextType == 3 ){
//
//                }
                
            }
            }else{
                //返回ERROR999991评定数据提交错误
//                NSString *msg = [backData objectForKey:@"msg"];
//                [Tools showMessage:msg view:self];
                if ([backData[@"code"] intValue] == 999991) {
                    ZLAlertView *alert = [[ZLAlertView alloc]initWithTitle:@"" message:@"请重拍或重新上传图片"];
                    [alert addBtnTitle:@"取消" action:^{
                        
                    }];
                    [alert addBtnTitle:@"确定" action:^{
                        [self.navigationController popViewControllerAnimated:NO];
                    }];
                    [alert showAlertWithSender:self];
                    
                }
                
            }
        } fail:^(NSError *error) {
            [SVProgressHUD dismiss];
            NSLog(@"%@",error.localizedDescription);
            [Tools showMessage:error.localizedDescription view:self];
        }];
        
    }
}
- (void)clickLeftbtnWith:(PopTipView *)popView
{
     [_PopJudgeCheck.leftBtn setImage:[UIImage imageNamed:@"yixuanze"] forState:UIControlStateNormal];
    isOKOrBad = _PopJudgeCheck.leftBtn.currentTitle;
    _PopJudgeCheck.changeIndex = 1;
    UIButton *btn = [_topView viewWithTag:667310 + 6];
    [btn setTitle:@"不合格" forState:UIControlStateNormal];
    isOKOrBad = @"不合格";
    [_OKBtn setImage:[UIImage imageNamed:@"weixuanze"] forState:UIControlStateNormal];
    [_BadBtn setImage:[UIImage imageNamed:@"yixuanze"] forState:UIControlStateNormal];
//    _OKBtn.selected = NO;
//    _BadBtn.selected = YES;
    _lastBtn = _BadBtn;
}

- (void)clickRightbtnWith:(PopTipView *)popView
{
    [_PopJudgeCheck.rightBtn setImage:[UIImage imageNamed:@"yixuanze"] forState:UIControlStateNormal];
     isOKOrBad = _PopJudgeCheck.rightBtn.currentTitle;
   
    _PopJudgeCheck.changeIndex = 2;
    UIButton *btn = [_topView viewWithTag:667310 + 6];
    [btn setTitle:@"合格" forState:UIControlStateNormal];
    isOKOrBad = @"合格";
    
    [_OKBtn setImage:[UIImage imageNamed:@"yixuanze"] forState:UIControlStateNormal];
    [_BadBtn setImage:[UIImage imageNamed:@"weixuanze"] forState:UIControlStateNormal];
//    _OKBtn.selected = YES;
//    _BadBtn.selected = NO;
    _lastBtn = _OKBtn;
}
- (void)addScrollView
{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64)];
    _scrollView.backgroundColor  = GrayBackColor;
    _scrollView.userInteractionEnabled = YES;
    [self.view addSubview:_scrollView];
}

- (void)addSubviews
{
    NSMutableDictionary *dict = [[NSUserDefaults standardUserDefaults] objectForKey:@"checkDict"];
   
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, space + 3, kScreenWidth, [UIView getHeight:200.0f])];
    _topView.backgroundColor = [UIColor whiteColor];
    
    [_scrollView addSubview:_topView];
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line1];
    
    CGFloat  imagew = 22.0f;
    
    UIImageView *infoImage = [[UIImageView alloc] initWithFrame:CGRectMake(2 * space,line1.maxY + space, imagew, imagew)];
    infoImage.image = [UIImage imageNamed:@"Btn_Normal_Xinxi"];
    //      [infoImage sd_setImageWithURL:[NSURL URLWithString:@"http://test.yun-gui.com/tools/show?path=./uploads/20150513/143151429747836.jpg"] placeholderImage:nil];
    //    infoImage.backgroundColor = BlueColor;
    //    infoImage.layer.cornerRadius = infoImage.width / 2.0f;
    //    infoImage.layer.masksToBounds = YES;
    [_topView addSubview:infoImage];
    
    UILabel  *infoLabel = [ViewTool getLabelWith:CGRectMake(infoImage.maxX +1.5 * space, infoImage.y, 150.0f, [UIView getHeight:18.0f]) WithTitle:@"基本信息" WithFontSize:15.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    [_topView addSubview:infoLabel];
    
    
    UIView *line2 = [ViewTool getLineViewWith:CGRectMake(infoLabel.x, infoLabel.maxY + space, kScreenWidth - infoLabel.x, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line2];
    
    NSArray * titleArra = @[@"网点编号",@"网点名称",@"检查时间",@"安装地址",@"百度坐标",@"柜体代数",@"是否合格"];
    CGFloat labelH = 20.0f;
    CGFloat labelW = 70.0f;
    
    for (int i = 0; i<titleArra.count ; i++) {
        UILabel *label = [ViewTool getLabelWith:CGRectMake(line2.x, line2.maxY + space +(space / 2.0f + labelH) * i, labelW, labelH) WithTitle:titleArra[i] WithFontSize:15.0f WithTitleColor:GRAYCOLOR WithTextAlignment:NSTextAlignmentLeft];
        //        label.backgroundColor = BlueColor;
        [_topView addSubview:label];
        if (i != titleArra.count - 1) {
            UILabel  *contentLabel = [ViewTool getLabelWith:CGRectMake(label.maxX + space,  label.y,  kScreenWidth - label.maxX - 2 * space,labelH) WithTitle:@" " WithFontSize:17.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
            //        contentLabel.backgroundColor = BlueColor;
            [_topView addSubview:contentLabel];
            
            contentLabel.tag = 667310 + i;
        
     
        if (i == 0) {
            contentLabel.text = dict[@"branch_NO"];
        }
        if (i == 1) {
            contentLabel.text = dict[@"branch_name"];
        }
        
        if (i ==2) {
            contentLabel.text = dict[@"check_at"];
        }
        if (i == 3) {
            contentLabel.text = dict[@"address"];
        }
        if (i == 4) {
            contentLabel.text = [NSString stringWithFormat:@"%@,%@",dict[@"longitude"],dict[@"latitude"]];
        }
        if (i == 5) {
            if ([dict[@"gen"] intValue] == 0) {
                 contentLabel.text = @"三代";
            }else{
                 contentLabel.text = @"五代";
            }
           
        }
    }
        if ( i== titleArra.count - 1) {
                _OKBtn = [[SettingButton alloc] initWithFrame:CGRectMake(label.maxX + space, label.y, 70.0f, label.height)];
                [_OKBtn setTitle:@"合格" forState:UIControlStateNormal];
            
                [_OKBtn setImage:[UIImage imageNamed:@"weixuanze.png"] forState:UIControlStateNormal];
            //    _OKBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            //    _OKBtn.backgroundColor = BlueColor;
            //    _OKBtn.titleLabel.textAlignment = NSTextAlignmentLeft;
            //    _OKBtn.contentEdgeInsets =UIEdgeInsetsMake(0, 5, 0, 0);
            //    _OKBtn.titleEdgeInsets = UIEdgeInsetsMake(0, -20, 0, 0);
                [_OKBtn setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
                [_OKBtn addTarget:self action:@selector(chooseQualified:) forControlEvents:UIControlEventTouchUpInside];
                _OKBtn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
//                _lastBtn = _OKBtn;
                _OKBtn.selected = NO;
            _OKBtn.tag = 6754290;
                [_topView addSubview:_OKBtn];
            
            
                _BadBtn = [[SettingButton alloc] initWithFrame:CGRectMake(_OKBtn.maxX + space, label.y, 80.0f, label.height)];
            //    [_BadBtn setImage:[UIImage imageNamed:@"Btn_Normal_Shijian"] forState:UIControlStateNormal];
                [_BadBtn setImage:[UIImage imageNamed:@"weixuanze.png"] forState:UIControlStateNormal];
            _BadBtn.tag = 6754291;
            //    _BadBtn.titleEdgeInsets = UIEdgeInsetsMake(0,-10, 0, 0);
            //    _BadBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            //    _BadBtn.backgroundColor = BlueColor;
                [_BadBtn addTarget:self action:@selector(chooseQualified:) forControlEvents:UIControlEventTouchUpInside];
                 [_BadBtn setTitle:@"不合格" forState:UIControlStateNormal];
                [_BadBtn setTitleColor:BLACKCOLOR forState:UIControlStateNormal];
                _BadBtn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
                _BadBtn.selected = NO;
                [_topView addSubview:_BadBtn];
            lastY = label.maxY;
        }
    }
    
    UIView *line3 = [ViewTool getLineViewWith:CGRectMake(0, lastY + 3 * space, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_topView addSubview:line3];
    _topView.frame = CGRectMake(0, space + 3, kScreenWidth, line3.maxY);
    
    //      NSLog(@"11  --%f",_topView.height);
}

- (void)chooseQualified:(SettingButton *)btn
{
//    if([btn.currentTitle isEqualToString:@"合格"]){
//
//    }
    if (_lastBtn != btn) {
        [_lastBtn setImage:[UIImage imageNamed:@"weixuanze.png"]  forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:@"yixuanze.png"] forState:UIControlStateNormal];
        _lastBtn.selected = NO;
        btn.selected = YES;
        _lastBtn = btn;
        isOKOrBad = btn.currentTitle;

    }
//    else{
//        if (btn.selected == YES) {
//           [ btn setImage:[UIImage imageNamed:@"yixuanze.png"] forState:UIControlStateNormal];
//        }else{
//           [ btn setImage:[UIImage imageNamed:@"weixuanze.png"] forState:UIControlStateNormal];
//        }
//        btn.selected = !btn.selected;
//    }
}
- (void)CallPopView
{
    _PopJudgeCheck = [[PopTipView alloc] initWithFrame:CGRectMake(0, 0, [UIView getWidth:200.0f], [UIView getHeight:120.0f])];
    //    _PopJudgeCheck.center = CGPointMake(kScreenWidth / 2.0f, kScreenHeight / 2.0f - 64);
    //    _PopJudgeCheck.backView.enabled = NO;
    _PopJudgeCheck.BackEnabled = NO;
    _PopJudgeCheck.tipsLabel.text = @"提示:请选择是否合格？";
    _PopJudgeCheck.lefttext = @"不合格";
    _PopJudgeCheck.righText = @"合格";
    _PopJudgeCheck.isShowImage = YES;
    _PopJudgeCheck.delegate = self;
    [_PopJudgeCheck showToView:self.view];
    

}
//备注部分
- (void)addThirdView
{
    _thirdView = [[UIView alloc] initWithFrame:CGRectMake(0, _topView.maxY + space +3, kScreenWidth , [UIView getHeight:120.0f])];
    _thirdView.backgroundColor = [UIColor whiteColor];
    [_scrollView addSubview:_thirdView];
    
    
    UIView *line1 = [ViewTool getLineViewWith:CGRectMake(0, 0, kScreenWidth, 1) withBackgroudColor:GRAYLINECOLOR];
    [_thirdView addSubview:line1];
    
    
    CGFloat  imagew = 22.0f;
    
    UIImageView *findImage = [[UIImageView alloc] initWithFrame:CGRectMake(2 * space,line1.maxY + space, imagew, imagew)];
    findImage.image = [UIImage imageNamed:@"Btn_Normal_Beizhu"];
    //    findImage.backgroundColor = BlueColor;
    //    findImage.layer.cornerRadius = findImage.width / 2.0f;
    //    findImage.layer.masksToBounds = YES;
    [_thirdView addSubview:findImage];
    
    UILabel  *findLabel = [ViewTool getLabelWith:CGRectMake(findImage.maxX +1.5 * space, findImage.y, 80.0f, 20.0f) WithTitle:@"备注说明" WithFontSize:15.0f WithTitleColor:BLACKCOLOR WithTextAlignment:NSTextAlignmentLeft];
    [_thirdView addSubview:findLabel];
    
    writeRecodView = [[MyTextView alloc] initWithFrame:CGRectMake(findLabel.maxX , findLabel.y - 8, _thirdView.width - findLabel.maxX, _thirdView.height - findLabel.y - space)];
    writeRecodView.textColor = BLACKCOLOR;
    writeRecodView.placehoder = @"请填写备注描述";
    writeRecodView.placehoderColor = GRAYCOLOR2;
    writeRecodView.delegate = self;
    writeRecodView.font = [UIFont systemFontOfSize:15.0f];
    [_thirdView addSubview:writeRecodView];
    
//    recordLabel = [ViewTool getLabelWith:CGRectMake(5, 5, writeRecodView.width, 20) WithTitle:@"请填写备注描述" WithFontSize:15.0f WithTitleColor:GRAYCOLOR2 WithTextAlignment:NSTextAlignmentLeft];
//    [writeRecodView addSubview:recordLabel];
    
    _scrollView.contentSize = CGSizeMake(kScreenWidth, _thirdView.maxY + 5);
    
}
- (void)textViewDidBeginEditing:(UITextView *)textView{
    
    if (recordLabel.hidden == NO) {
        [UIView animateWithDuration:0.1 animations:^{
            recordLabel.hidden = YES;
        }];
    }
}

- (void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0 || [textView.text isEqualToString:@""]) {
        if (recordLabel.hidden == YES) {
            [UIView animateWithDuration:0.1 animations:^{
                recordLabel.hidden = NO;
            }];
            writeRecodView.text = @"";
        }
    }
}
- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)backController
{
    [self.navigationController popViewControllerAnimated:YES];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
